package org.shoukaiseki.test.business.user.controller;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.shoukaiseki.test.common.view.ResultModel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class FileUploadController {


    @ResponseBody
    @PostMapping(path = "/upload")
    public ResultModel upload(@RequestParam(value="file") MultipartFile uploadFile){
        ResultModel result=new ResultModel();
        String saveDir = System.getProperty("user.dir");
        saveDir+="/target/uploadfile";
        File dirFile = new File(saveDir);
        //目录不存在则创建,存放到maven的编译目录,可以在mavenclean时候删除
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String name = uploadFile.getOriginalFilename();
        String suffix=".png";
        Map<String,Object> data=new HashMap<>();
        data.put("uploadFile.OriginalFilename",name);
        if(!StringUtils.isBlank(name)){
            suffix=name.substring(name.lastIndexOf("."));
            data.put("解析到的后缀名",suffix);
        }else{
            data.put("默认后缀名",suffix);
        }
        result.setData(data);
        String filename = saveDir +"/"+ System.currentTimeMillis() + System.nanoTime()+suffix;
        result.setMsg(filename);
        File file = new File(filename);
        try {
            FileUtils.copyInputStreamToFile(uploadFile.getInputStream(),file);
        } catch (IOException e) {
            e.printStackTrace();
            result.setMsg("保存文件失败"+filename);
        }

        return result;
    }
}
